import React, { useState,useEffect } from 'react';
import { Upload, Button, Spin, message } from 'antd';
import { DownloadOutlined, UploadOutlined } from '@ant-design/icons';
import ExcelJS from 'exceljs';


//报价单纯小部件导入
const ExcelComponent = () => {
  const [loading, setLoading] = useState(false);
  const [qutoteinfo, setQutoteinfo] = useState(false);

  const handleDownload = async () => {
    setLoading(true);
    const link = `https://files.zohopublic.com.cn/public/workdrive-public/download/vrz5k054f364af06546b3a25202d714f5961c?x-cli-msg={"linkId":"1nHCl5jpBFs-31RIu","isFileOwner":false}`;
    try {
      window.location.href = link;
    } catch (error) {
      console.error('下载文件失败:', error);
      message.error('下载文件失败！');
    }finally{
      setLoading(false);
    }
  };
  useEffect(() => {
    const initialize = async () => {
      await window.zohoReadyPromise;

      setQutoteinfo( window.wdata?.Data);
      console.log("ZOHO is ready", window.wdata?.Data);
    };
    initialize();
  }, []);

  const dataset = async(exceljsondata) =>{
    var { Quotation_PDetails ,ExchangeRate ,Quotationmethod} = qutoteinfo;

    console.log('Quotation_PDetails',Quotation_PDetails);
    if(exceljsondata && exceljsondata.length > 0){

      // 过滤掉所有属性都为null的对象
      const filteredArray = Quotation_PDetails.filter(item => {
        return !(item.AccountprtNo === null || item.AccountprtNo === "" && item.Englishname === null || item.Englishname === "" && item.internalcode === null || item.internalcode === "");
      });
        //Products
        console.log('filteredArray',filteredArray);  
        
        for (const row of exceljsondata) {
          var pdname = row['商品编码'];
          var pdinfo = null;
          if (pdname) {
              var seapd = await window.ZOHO.CRM.API.searchRecord({Entity:"Products",Type:"criteria",Query:"Product_Name:equals:" + encodeURIComponent(pdname)})
              // console.log('seapd', seapd);
              if (seapd && seapd.data.length > 0) {
                  pdinfo = { id: seapd.data[0].id, name: seapd.data[0].Product_Name };
              }
          }
          var data_tempinfo = {
              Product: pdinfo,
              AccountprtNo: row['客户货号'],
              internalcode: row['内部货号'],
              Englishname: row['英文品名'],
              Specification: row['英文规格'],
              Brand: row['品牌'],
              Unit: row['单位'],
              Exportprice: row['商品库外销价格G'],
              Profit: row['利润'],
              Costfee: row['成本费'],
              Processingfee: row['加工费'],
              Sterilizationfee: row['杀菌费'],
              Smallpackage: row['小包+'],
              Bigbag: row['大包+'],
              Carton: row['纸箱'],
              Nuofboxesinpg: row['入数'],
              Nuofboxeinnerbox: row['内盒数'],
              Netweightofinnebox: row['单净重G'],
              Lengthofouterbox: row['长CM'],
              Cartonwidth: row['宽CM'],
              Heightofouterbox: row['高CM'],
              Grossweight: row['毛重KG'],
              Packaginunit: row['包装单位'],
              PackagesNumber: row['包装包数'],
              former_price: row['former price'],
              Shelflife: row['保质期'],
              HSCode: row['HS编码'],
              Productname: row['中文品名'],
              Remarks: row['商品备注'],
              Chptrequirements_material: row['中文生产要求(材质)'],
              ChinesePackagedesp: row['中文包装描述'],
              Chineseingredients: row['中文成份'],
              Chinesespecification: row['中文规格'],
          }

          var ExchangeRate_fromt = parseFloat(ExchangeRate) || 1;
          
          const Costfee = parseFloat(data_tempinfo.Costfee) || 0;
          const Processingfee = parseFloat(data_tempinfo.Processingfee) || 0;
          const Profit = parseFloat(data_tempinfo.Profit) || 0;
          const Sterilizationfee = parseFloat(data_tempinfo.Sterilizationfee) || 0;
          const Smallpackage = parseFloat(data_tempinfo.Smallpackage) || 0;
          const Quantityperbox = parseFloat(data_tempinfo.Quantityperbox) || 1;
          const Bigbag = parseFloat(data_tempinfo.Bigbag) || 0;
          const Nuofboxeinnerbox = parseFloat(data_tempinfo.Nuofboxeinnerbox) || 0;
          const Carton = parseFloat(data_tempinfo.Carton) || 0;
          var RMB_Opticalplate = ((Costfee + Processingfee) * (1 + Profit / 100)) + Sterilizationfee;
          var USD_Opticalplate = RMB_Opticalplate / ExchangeRate_fromt;
          const Netweightofinnebox = parseFloat(data_tempinfo.Netweightofinnebox) || 0;

          console.log('data_tempinfo.Netweightofinnebox', data_tempinfo.Netweightofinnebox);
          console.log('Netweightofinnebox',Netweightofinnebox);

          var USD_Finalquotation = 0;
          data_tempinfo.USD_Opticalplate = parseFloat(USD_Opticalplate.toFixed(3));
          data_tempinfo.RMB_Opticalplate = parseFloat(RMB_Opticalplate.toFixed(3));;
          const Netweight = parseFloat(`${(data_tempinfo.Netweightofinnebox * data_tempinfo.Nuofboxesinpg * data_tempinfo.Nuofboxeinnerbox)/1000}`) || 1; // 防止除以0

          if (Quotationmethod == "公斤报价") {
              var Packagingfee = (Smallpackage * Quantityperbox + Bigbag * Nuofboxeinnerbox + Carton) / Netweight * 1.03
              USD_Finalquotation = (RMB_Opticalplate + Packagingfee) / ExchangeRate_fromt;
              var USD_Exportkilogramprice = USD_Finalquotation / (Netweightofinnebox / 1000);

              data_tempinfo.Packagingfee = Packagingfee;
              data_tempinfo.USD_Exportkilogramprice = USD_Exportkilogramprice;
              data_tempinfo.USD_Finalquotation = USD_Finalquotation;

          } else if (Quotationmethod == "包装袋报价") {

              var Packagingfee = (Smallpackage * Quantityperbox + Bigbag * Nuofboxeinnerbox + Carton) / Quantityperbox * 1.03

              //（（报价KGRMB光板/1000*包装内盒单净重G）+报价RMB包装费=）/汇率      
              USD_Finalquotation = ((RMB_Opticalplate * Netweightofinnebox / 1000) + Packagingfee) / ExchangeRate_fromt;

              //usd 最终报价 =（(RMB光板/1000*单重) +包装费)/汇率);
              // var USD_Exportkilogramprice = (((RMB_Opticalplate / 1000) * Netweightofinnebox ) + Packagingfee) / ExchangeRate_fromt ;
              var USD_Exportkilogramprice = USD_Finalquotation / (Netweightofinnebox / 1000);
              data_tempinfo.Packagingfee = Packagingfee;
              data_tempinfo.USD_Exportkilogramprice = USD_Exportkilogramprice;
              data_tempinfo.USD_Finalquotation = USD_Finalquotation;


          }  else if (Quotationmethod == "整箱报价") {

              var Packagingfee = (Smallpackage * Quantityperbox + Bigbag * Nuofboxeinnerbox + Carton) * 1.03
              USD_Finalquotation = ((RMB_Opticalplate / 1000 * Netweight) + Packagingfee) / ExchangeRate_fromt;
              var USD_Exportkilogramprice = USD_Finalquotation / (Netweightofinnebox / 1000);
              data_tempinfo.Packagingfee = Packagingfee;
              data_tempinfo.USD_Exportkilogramprice = USD_Exportkilogramprice;
              data_tempinfo.USD_Finalquotation = USD_Finalquotation;
          }


          filteredArray.push(data_tempinfo);
      };


      console.log('filteredArray', filteredArray);
      await window.ZOHO.CRM.UI.Record.populate({
        Quotation_PDetails:[]
      });
      await window.ZOHO.CRM.UI.Record.populate({
        Quotation_PDetails:filteredArray
      });





    }
  }

  const handleImport = async(options) => {
    const { file, onSuccess, onError } = options;
    setLoading(true);
    const reader = new FileReader();
    reader.onload = async (e) => {
      try {
        const arrayBuffer = e.target.result;
        const workbook = new ExcelJS.Workbook();
        await workbook.xlsx.load(arrayBuffer);

        const worksheet = workbook.worksheets[0]; // 只处理第一个工作表
        const exceljsondata = [];
        const headers = [];

        worksheet.eachRow((row, rowNumber) => {
          if (rowNumber === 1) {
            row.eachCell((cell) => {
              headers.push(cell.value);
            });
          } else {
            const rowData = {};
            row.eachCell((cell, colNumber) => {
              rowData[headers[colNumber - 1]] = cell.value;
            });
            exceljsondata.push(rowData);
          }
        });
        console.log('exceljsondata',exceljsondata);
        await dataset(exceljsondata);
        setLoading(false);
        onSuccess('ok');


      } catch (error) {
        console.error('文件上传失败:', error);
        setLoading(false);
        onError(error);
        message.error('文件上传失败！');
      }
    };
    reader.onerror = (error) => {
      console.error('文件读取失败:', error);
      setLoading(false);
      onError(error);
      message.error('文件读取失败！');
    };
    reader.readAsArrayBuffer(file);
  };


  return (
    <Spin spinning={loading}>
      <div style={{ padding: '20px', height: '90vh' }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', justifyContent: 'flex-start', marginBottom: '20px' }}>
          <Button type="link" onClick={handleDownload} icon={<DownloadOutlined />} style={{ marginBottom: 20 }}>
            下载 Excel 模板文件
          </Button>
          <Upload
            name="file"
            customRequest={handleImport}
            showUploadList={false}
            accept=".xlsx,.xls"
          >
            <Button type="primary" icon={<UploadOutlined />}>导入 Excel</Button>
          </Upload>
        </div>
      </div>
    </Spin>
  );
  
};

export default ExcelComponent;
